package com.zmj.controller;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zmj.entity.SysUser;
import com.zmj.service.UserService;
import com.zmj.utils.JWTUtils;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @RequestMapping("/login")
    public Map<String,Object> login(SysUser user){
        logger.info("用户名称: {}",user.getName());
        logger.info("用户密码: {}",user.getPassword());

        Map<String,Object> map = new HashMap<>();
        try {
            SysUser userDb = userService.login(user);
            HashMap<String, String> payload = new HashMap<>();
            payload.put("id",userDb.getId());
            payload.put("name",userDb.getName());

            String token = JWTUtils.getToken(payload);
            map.put("state",true);
            map.put("msg","认证成功");
            map.put("token",token);
        } catch (Exception e) {
            logger.info("异常： {}",e);
            map.put("state",false);
            map.put("msg","认证失败");
        }
        return map;
    }


    @RequestMapping("/test")
    public Map<String,Object> test(){
        Map<String, Object> map = new HashMap<>();
        map.put("state",true);
        map.put("msg","操作成功!!!");
        return map;
    }

    @RequestMapping("/testgetInfo")
    public Map<String,Object> testgetInfo(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();

        String token = request.getHeader("token");
        DecodedJWT verify = JWTUtils.verify(token);
        logger.info("用户id: {}",verify.getClaim("id").asString());
        logger.info("用户名: {}",verify.getClaim("name").asString());

        map.put("state",true);
        map.put("msg","操作成功");
        return map;
    }


}
